<!DOCTYPE html>
<html>
<head>
    <title>API 调试工具</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background: #f0f2f5;
        }
        .container {
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        #output {
            white-space: pre-wrap;
            background: #f5f5f5;
            padding: 15px;
            border-radius: 5px;
            margin-top: 20px;
            min-height: 200px;
        }
        .message {
            margin: 5px 0;
            padding: 5px;
            border-bottom: 1px solid #eee;
        }
        .error {
            color: red;
        }
        .done {
            color: green;
        }
        button {
            background: #1890ff;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 5px;
            transition: all 0.3s;
        }
        button:hover {
            background: #40a9ff;
            transform: translateY(-1px);
        }
        button.secondary {
            background: #f5f5f5;
            color: #666;
            border: 1px solid #d9d9d9;
        }
        button.secondary:hover {
            background: #e6e6e6;
            border-color: #40a9ff;
            color: #40a9ff;
        }
        .button-group {
            display: flex;
            gap: 10px;
            margin: 10px 0;
        }
        textarea {
            width: 100%;
            padding: 10px;
            margin: 10px 0;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
    </style>
</head>
<body>
    <h1>API 调试工具</h1>
    
    <div class="container">
        <h2>Coze 聊天</h2>
        <div>
            <textarea id="content" rows="4" placeholder="输入消息内容"></textarea>
            <div class="button-group">
                <button onclick="sendMessage()">发送消息</button>
                <button class="secondary" onclick="clearOutput()">清除输出</button>
            </div>
        </div>
        <div id="output"></div>
    </div>

    <div class="container">
        <h2>假数据生成</h2>
        <div class="button-group">
            <button onclick="getFakeData('data')">生成全部数据</button>
            <button onclick="getFakeData('phone')">生成手机号</button>
            <button onclick="getFakeData('uuid')">生成UUID</button>
            <button onclick="getFakeData('timestamp')">生成时间戳</button>
            <input type="number" id="count" value="1" min="1" max="100" style="width: 60px; padding: 8px;">
            <span style="line-height: 40px;">条</span>
            <button class="secondary" onclick="clearFakeOutput()">清除输出</button>
        </div>
        <div id="fakeOutput" style="margin-top: 20px;"></div>
    </div>

    <script>
        const output = document.getElementById('output');
        let eventSource = null;

        function appendMessage(text, type = '') {
            const div = document.createElement('div');
            div.className = `message ${type}`;
            div.textContent = text;
            output.appendChild(div);
            output.scrollTop = output.scrollHeight;
        }

        function clearOutput() {
            output.innerHTML = '';
        }

        function closeEventSource() {
            if (eventSource) {
                eventSource.close();
                eventSource = null;
            }
        }

        function clearFakeOutput() {
            document.getElementById('fakeOutput').innerHTML = '';
        }

        async function getFakeData(type) {
            const count = document.getElementById('count').value;
            const output = document.getElementById('fakeOutput');
            output.innerHTML = '加载中...';

            try {
                const response = await fetch(`/fake/${type}?count=${count}`);
                const data = await response.json();
                output.innerHTML = `<pre>${JSON.stringify(data, null, 2)}</pre>`;
            } catch (error) {
                output.innerHTML = `<div class="error">错误: ${error.message}</div>`;
            }
        }

        async function sendMessage() {
            closeEventSource();
            const content = document.getElementById('content').value;
            if (!content) {
                alert('请输入消息内容');
                return;
            }

            clearOutput();
            appendMessage('发送消息: ' + content);

            try {
                const response = await fetch('/chat', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ content }),
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                if (response.headers.get('content-type').includes('text/event-stream')) {
                    const reader = response.body.getReader();
                    const decoder = new TextDecoder();
                    let buffer = '';

                    while (true) {
                        const { value, done } = await reader.read();
                        if (done) break;

                        buffer += decoder.decode(value, { stream: true });
                        const lines = buffer.split('\n\n');
                        buffer = lines.pop() || '';

                        for (const line of lines) {
                            if (line.trim()) {
                                const [eventLine, dataLine] = line.split('\n');
                                const eventType = eventLine.replace('event: ', '');
                                const data = JSON.parse(dataLine.replace('data: ', ''));

                                switch (eventType) {
                                    case 'message':
                                        if (data.data && data.data.text) {
                                            appendMessage(data.data.text);
                                        } else {
                                            appendMessage(JSON.stringify(data, null, 2));
                                        }
                                        break;
                                    case 'error':
                                        appendMessage(JSON.stringify(data, null, 2), 'error');
                                        break;
                                    case 'done':
                                        appendMessage('完成', 'done');
                                        break;
                                }
                            }
                        }
                    }
                } else {
                    // 非流式响应
                    const data = await response.json();
                    if (data.data && data.data.text) {
                        appendMessage(data.data.text);
                    } else {
                        appendMessage(JSON.stringify(data, null, 2));
                    }
                    appendMessage('完成', 'done');
                }
            } catch (error) {
                appendMessage('错误: ' + error.message, 'error');
            }
        }
    </script>
</body>
</html>
